/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package gui;

import interfaces.EditPanel;

import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import server.IntelServerType;
import tools.InputType;
import tools.StringTools;
import database.DBConnectionFactory;

/**
 * Settings panel for services
 * 
 * 
 */
public class ServicesPanel extends JPanel implements EditPanel {
   private static final long serialVersionUID = 4228896307757033356L;
   private JTextField port;
   private JComboBox serverType;
   private JCheckBox run;
   private String itemName;
   private final DialogPanel parent;

   public ServicesPanel(final DialogPanel parent) {
	  super();
	  this.parent = parent;
	  initialize();
   }

   @Override
   public final void checkInputs() {
	  if (!StringTools.validateInput(InputType.INT, port.getText())) {
		 parent.setSaveButtonEnabled(false);
	  } else {
		 parent.setSaveButtonEnabled(true);
	  }
   }

   @Override
   public boolean delete() {
	  // do nothing
	  return false;
   }

   @Override
   public String getItemName() {
	  return itemName;
   }

   /**
    * Initializes the components
    */
   private void initialize() {
	  setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
	  port = new JTextField();
	  port.setPreferredSize(new Dimension(300, 20));
	  port.getDocument().addDocumentListener(new MyDocumentListener(this));
	  serverType = new JComboBox(IntelServerType.toStringList());
	  serverType.setEditable(false);
	  serverType.addItemListener(new ItemListener() {
		 @Override
		 public void itemStateChanged(final ItemEvent e) {
			checkInputs();
		 }
	  });
	  run = new JCheckBox();
	  run.setPreferredSize(new Dimension(300, 20));
	  run.setText("Select to run on startup");
	  run.addChangeListener(new javax.swing.event.ChangeListener() {
		 @Override
		 public void stateChanged(final javax.swing.event.ChangeEvent e) {
			checkInputs();
		 }
	  });

	  this.add(new CustomPanel(new CustomLabel("Port", 80, 20), port));
	  this.add(new CustomPanel(new CustomLabel("Server Type", 80, 20), serverType));
	  this.add(new CustomPanel(new CustomLabel("Run", 80, 20), run));
   }

   @Override
   public JPanel load(final String item) {
	  itemName = item;
	  removeAll();
	  validate();
	  initialize();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM settings WHERE id = 0");
		 rs = ps.executeQuery();

		 if (rs.next()) {
			port.setText(rs.getString(item + "port"));
			run.setSelected(rs.getBoolean("run" + itemName));
			if (item.equals("intel")) {
			   serverType.setEnabled(true);
			   serverType.setSelectedItem(rs.getString("intelservertype"));
			} else {
			   serverType.setEnabled(false);
			}
		 } else {
			port.setText(item);
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return this;
   }

   @Override
   public boolean save() {
	  if (!StringTools.validateInput(InputType.INT, port.getText()))
		 return false;
	  PreparedStatement ps = null;
	  boolean success = false;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("UPDATE settings SET " + itemName + "port = ?,run" + itemName + " = ? WHERE id = 0");
		 ps.setInt(1, Integer.parseInt(port.getText()));
		 ps.setBoolean(2, run.isSelected());
		 ps.executeUpdate();

		 if (itemName.equals("intel")) {
			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("UPDATE settings SET intelservertype = ?");
			ps.setString(1, serverType.getSelectedItem().toString());
			ps.executeUpdate();
		 }

		 success = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return success;
   }
}
